	var id,
	    posx,
	    posy,
	    movex = 0,
	    movey = 0,
	    movek = 1,
	    locked = false,
	    width = 0,
	    height = 0,
	    img_w = 30,
	    img_h = 30,
	    radius = 15,
	    svg,
	    force,
	    links,
	    nodes,
	    gs,
	    outer,
	    nodes_txt,
	    graph = { "nodes": [], "links": [] };

	layui.use('table', function() {
	    var table = layui.table;

	    table.render({
	        elem: '#test',
	        url: 'json/sx-list.json',
	        cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
	            ,
	        cols: [
	            [
	                { field: 'id', width: 280, title: '关联类型名称', sort: true }, { field: 'username', title: 'URL' }, { field: 'sex', width: 280, title: '已弃用', sort: true }
	            ]
	        ]
	    });
	});

	//右键菜单操作
	var userMenuData = [
	    [{
	            text: "删除实例",
	            data: [
	                [{
	                    text: "删除自身",
	                    func: function() {
	                        nodedelete(id);
	                    }
	                }, {
	                    text: "删除关联事件",
	                    func: function() {
	                        relationDel('Event');
	                    }
	                }, {
	                    text: "删除关联实体",
	                    func: function() {
	                        relationDel('Entity');
	                    }
	                }, {
	                    text: "删除关联文件",
	                    func: function() {
	                        relationDel('Doc');
	                    }
	                }, {
	                    text: "删除关联媒体",
	                    func: function() {
	                        relationDel('Media');
	                    }
	                }]
	            ]
	        },
	        {
	            text: "属性",
	            func: function() {
	                window.location.href = "obj-show-obj.html";
	            }
	        },
	        {
	            text: "关联",
	            data: [
	                [{
	                    text: "关联事件",
	                    func: function() {
	                        var primaryId = $('input[name=primaryId]').val(),
	                            primaryRowkey = $('input[name=primaryRowkey]').val();
	                        relationEvents(primaryId, primaryRowkey);
	                    }
	                }, {
	                    text: "关联实体",
	                    func: function() {
	                        var primaryId = $('input[name=primaryId]').val(),
	                            primaryRowkey = $('input[name=primaryRowkey]').val();
	                        relationEntity(primaryId, primaryRowkey);
	                    }
	                }, {
	                    text: "关联文件",
	                    func: function() {
	                        var primaryId = $('input[name=primaryId]').val(),
	                            primaryRowkey = $('input[name=primaryRowkey]').val();
	                        relationDoc(primaryId, primaryRowkey);
	                    }
	                }, {
	                    text: "关联多媒体",
	                    func: function() {
	                        var primaryId = $('input[name=primaryId]').val(),
	                            primaryRowkey = $('input[name=primaryRowkey]').val();
	                        relationMedia(primaryId, primaryRowkey);
	                    }
	                }]
	            ]
	        },
	        {
	            text: "关系融合",
	            func: function() {
	                console.log('菜单2：' + id);
	            }
	        },
	        {
	            text: "收缩事件",
	            func: function() {
	                console.log('菜单2：' + id);
	            }
	        },
	        {
	            text: "最短路径",
	            func: function() {
	                console.log('菜单2：' + id);
	            }
	        }
	    ]
	];

	//graph格式化
	function graphFormat(graph) {
	    var linkold = graph["links"];
	    if (linkold.length > 0) {
	        var obj = typeof(linkold[0]['source']);
	        if (obj == 'object') {
	            var linkTemp = [];
	            for (var j = 0; j < linkold.length; j++) {
	                linkTemp[j] = { "source": linkold[j]["source"].index, "target": linkold[j]["target"].index, "relation": linkold[j]["relation"], "timeInterval": linkold[j]["timeInterval"], "value": linkold[j]["value"], "index": linkold[j]["index"] };
	            }
	            graph["links"] = linkTemp;
	        }
	    }
	    return graph;
	}

	//获取关联图数据
	function getGraph() {
	    $.ajax({
	        type: 'get',
	        url: unifiedUserUrl + '/relationgraph',
	        async: false,
	        xhrFields: { withCredentials: true },
	        success: function(result) {

	            if (result != '' && result != null) {
	                //console.log('ww:'+result.data);
	                graph = JSON.parse(result.data);
	                graph = graphFormat(graph);
	            }
	        }
	    });
	}


	var img1 = '';

	//初始数据
	/*graph ={
		"nodes": [
			{"index":0, "name":"湖南邵阳", "image":img1, "x":681, "y":155, "uri":"com.scistor.object.luyin", "rowkey":"LUYIN_53933BF037C49E6E98AEFC490F88367F"},
			{"index":1, "name":"山东莱州", "image":img1, "x":269, "y":379, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"},
			{"index":2, "name":"广东阳江", "image":img1, "x":352, "y":46, "uri":"com.scistor.object.entity.person", "rowkey":"ENTITY_PERSON_4C9C1D8F7AB560C8F73992D91325252F"},
			{"index":3, "name":"山东枣庄", "image":img1, "x":622, "y":283, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"},
			{"index":4, "name":"泽", "image":img1, "x":490, "y":117, "uri":"com.scistor.object.luyin", "rowkey":"LUYIN_E0FE1C8AD7F1FACE9CAFD177BF032195"},
			{"index":5, "name":"恒", "image":img1, "x":169, "y":119, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"},
			{"index":6, "name":"鑫", "image":img1, "x":3, "y":277, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"},
			{"index":7, "name":"明山", "image":img1, "x":389, "y":226, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"},
			{"index":8, "name":"班长", "image":img1, "x":485, "y":329, "uri":"com.scistor.object.entity_person", "rowkey":"ENTITY_PERSON_84D9DFD1A2E9A1A264B62A4047563296"}
		],
		"links": [
			{"source":0, "target":4, "relation":"籍贯", "value":1.3},
			{"source":4, "target":5, "relation":"舍友", "value":1},
			{"source":4, "target":6, "relation":"舍友", "value":1},
			{"source":4, "target":7, "relation":"舍友", "value":1},
			{"source":1, "target":6, "relation":"籍贯", "value":2},
			{"source":2, "target":5, "relation":"籍贯", "value":0.9},
			{"source":3, "target":7, "relation":"籍贯", "value":1},
			{"source":5, "target":6, "relation":"同学", "value":1.6},
			{"source":6, "target":7, "relation":"朋友", "value":0.7},
			{"source":6, "target":8, "relation":"职责", "value":2}
		]
	}*/
	getGraph();

	//console.log(graph);

	//获取cookie数据创建新节点
	function creatNewNodes(newNodes) {

	    if (newNodes != null && newNodes != 'null') {

	        newNodes = JSON.parse(newNodes);

	        var nodeslen = graph["nodes"].length;
	        for (var i = 0; i < newNodes.length; i++) {
	            var icon = '';
	            //获取实体名称、头像
	            $.ajax({
	                type: 'get',
	                url: unifiedUserUrl + 'object/' + newNodes[i]["objectUri"],
	                async: false,
	                xhrFields: { withCredentials: true },
	                success: function(data) {
	                    console.log('ico:' + data);
	                    icon = data.icon;
	                }
	            });
	            var tempx = getRandom(15, 1040),
	                tempy = getRandom(15, 385);
	            graph["nodes"][nodeslen] = { "index": nodeslen, "name": newNodes[i]["displayName"], "image": icon, "x": tempx, "y": tempy, "uri": newNodes[i]["objectUri"], "rowkey": newNodes[i]["rowKey"] };
	            nodeslen++;
	        }
	        $('#container2 svg').html('');
	        createForce(graph, userMenuData);

	        //graph=graphFormat(graph);
	        $.ajax({
	            type: 'POST',
	            url: unifiedUserUrl + '/relationgraph',
	            data: { 'data': JSON.stringify(graph) },
	            async: true,
	            xhrFields: { withCredentials: true },
	            success: function(data, textStatus) {
	                if (textStatus == 'success') {}
	            }
	        });

	        setCookie('objdetailData', null)
	    }
	}

	function createForce(graph, userMenuData) {

	    console.log('df:' + graph);

	    svg = d3.select("svg"),
	        g = svg.append("g");
	    width = svg.attr("width");
	    height = svg.attr("height");


	    var zoom = d3.zoom()
	        .scaleExtent([1, 1])
	        .on("zoom", function() { // zoom事件
	            g.attr("transform", d3.zoomTransform(svg.node()));
	            nodes.attr("transform", d3.zoomTransform(svg.node()));
	            movex = d3.zoomTransform(svg.node()).x;
	            movey = d3.zoomTransform(svg.node()).y;
	            movek = d3.zoomTransform(svg.node()).k;
	        });

	    svg.call(zoom);


	    //新建一个力导向图
	    force = d3.forceSimulation()
	        .force("charge", d3.forceManyBody())
	        //.force("center",d3.forceCenter(width/2,height/2))
	        .on("tick", ticked);

	    //初始化力导向图，也就是传入数据
	    //生成节点数据
	    force.nodes(graph.nodes)
	        .force("link", d3.forceLink(graph.links));

	    //生成边数据
	    links = g.selectAll("link")
	        .data(graph.links)
	        .enter()
	        .append("line")
	        //.attr("style", "stroke:#999; stroke-width:1.5px;")
	        .attr("style", function(d, i) {
	            if (d.color) {
	                return "stroke:" + d.color + "; stroke-width:1.5px;";
	            } else {
	                return "stroke:#999; stroke-width:1.5px;";
	            }
	        });

	    //绘制节点
	    //老规矩，先为节点和节点上的文字分组
	    nodes = svg.selectAll("image")
	        .data(graph.nodes, function(currentNode, index) {
	            return currentNode.name;
	        })
	        .enter()
	        .append("g")
	        .attr("class", "g-item")
	        .attr("vl", function(d, i) {
	            return i;
	        })
	        .call(d3.drag()
	            .on("start", dragstart)
	            .on("drag", dragged)
	            .on("end", dragended)
	        );

	    //添加外部圆
	    outer = nodes.append("circle")
	        .attr("r", function(d) {
	            return radius + 4;
	        })
	        .attr("class", "outer");

	    gs = nodes
	        .append("circle")
	        .attr("style", "stroke:#ccc;stroke-width:1.5px;")
	        .attr("r", radius)
	        .attr("fill", function(d, i) {
	            return "url(#catpattern" + i + ")";
	        })



	    gs.on("contextmenu", function(d, i) {
	        id = d.index;
	        posx = d.x + 7 + movex;
	        posy = d.y + 100 + movey;

	        $('input[name=posx]').val(posx);
	        $('input[name=posy]').val(posy);
	        $('input[name=primaryId]').val(d.uri);
	        $('input[name=primaryRowkey]').val(d.rowkey);

	        $("circle").smartMenu(userMenuData, {
	            name: "circle"
	        });
	        d3.event.preventDefault();
	    });

	    nodes.on("click", function(d, i) {

	        var uri = d.uri,
	            rowkey = d.rowkey,
	            title = d.name;
	        $('#objShow').html(getExample(uri, rowkey, title));

	    });

	    $("circle").smartMenu(userMenuData, {
	        name: "circle"
	    });

	    var nodes_img = nodes.append("pattern")
	        .attr("id", function(d, i) {
	            return "catpattern" + i;
	        })
	        .attr("height", 1)
	        .attr("width", 1)
	        .append("image")
	        .attr("x", -(img_w / 2 - radius))
	        .attr("y", -(img_h / 2 - radius))
	        .attr("width", img_w)
	        .attr("height", img_h)
	        .attr("xlink:href", function(d, i) {
	            return d.image;
	        })


	    //文字
	    nodes_txt = nodes.append("text")
	        .text(function(d) {
	            return d.name;
	        })

	}



	function ticked() {

	    links.attr("x1", function(d) { return d.source.x; })
	        .attr("y1", function(d) { return d.source.y; })
	        .attr("x2", function(d) { return d.target.x; })
	        .attr("y2", function(d) { return d.target.y; });

	    nodes.attr("cx", function(d) { d.fx = d.x; return d.x; })
	        .attr("cy", function(d) { d.fy = d.y; return d.y; });

	    gs.attr("cx", function(d) { d.fx = d.x; return d.x; })
	        .attr("cy", function(d) { d.fy = d.y; return d.y; });

	    outer.attr("cx", function(d) { d.fx = d.x; return d.x; })
	        .attr("cy", function(d) { d.fy = d.y; return d.y; });

	    nodes_txt.attr("x", function(d) { return d.x - 10; })
	        .attr("y", function(d) { return d.y + img_w / 2 + 20; });

	}

	if (graph['nodes'].length > 0) {
	    createForce(graph, userMenuData);
	} else {
	    /*layer.msg('请添加节点信息！', {
	      	time: 2000
	    });*/
	}

	//获取cookie
	var newNodes = unescape(getCookie('objdetailData'));
	//console.log(newNodes);
	creatNewNodes(newNodes)


	function dragstart(d) {
	    if (isChecked()) {
	        var uri = $('input[name=secondaryId]').val(d.uri),
	            rowkey = $('input[name=secondaryRowkey]').val(d.rowkey),
	            secondaryvl = $('input[name=secondaryvl]').val(d.index);

	        createRelation();

	    } else if (isbeeline()) {
	        var uri = $('input[name=secondaryId]').val(d.uri),
	            rowkey = $('input[name=secondaryRowkey]').val(d.rowkey),
	            secondaryvl = $('input[name=secondaryvl]').val(d.index);

	        shortestPath();
	    } else {

	        var uri = $('input[name=primaryId]').val(d.uri),
	            rowkey = $('input[name=primaryRowkey]').val(d.rowkey),
	            primaryvl = $('input[name=primaryvl]').val(d.index);

	        nodes.classed("selected", function() {
	            return d.selected = false;
	        })

	        d3.select(this).classed("selected", function(p) {
	            d.previouslySelected = d.selected;
	            return d.selected = true;
	        });

	    }

	    if (!d3.event.active) {
	        force.alphaTarget(.1).restart();
	    }
	    d.fx = d.x;
	    d.fy = d.y;
	}

	function dragged(d) {
	    //console.log('ddddd:'+d3.event.x);
	    d.fx = d3.event.x;
	    d.fy = d3.event.y;
	}

	function dragended(d) {
	    // force.stop();
	    if (!d3.event.active) {
	        force.alphaTarget(0);
	    }
	    // d.fx = null;
	    // d.fy = null;
	}


	$('.drawTree').on('click', function() {
	    drawTree();
	});

	//绘制树状布局
	function drawTree() {
	    console.log($('svg').width());
	    var svg_w = $('svg').width();
	    var middleData = {};
	    var linksBak = graph["links"].concat();
	    var nodesBak = graph["nodes"].concat();


	    /*linksBak.forEach(function(lk){
	    	console.log(lk);
	    });*/
	    var level = 0;
	    for (var i = 0; i < linksBak.length; i++) {
	        if (i == 0) {
	            var idx = linksBak[i]['source'].index;

	            /*linksBak[i]['source'].x=450;
	            linksBak[i]['source'].y=450;*/

	            nodesBak[idx]["fx"] = svg_w / 2;
	            nodesBak[idx]["fy"] = 25;

	            console.log(nodesBak[idx]);

	            level++;
	        }
	        //console.log(linksBak[i]);



	    }
	    graph["links"] = linksBak;
	    graph["nodes"] = nodesBak;


	    graph = graphFormat(graph);

	    console.log(graph);
	    $('#container2 svg').html('');
	    createForce(graph, userMenuData);

	    /*nodesBak.forEach(function(d){
			if(d.index == 0){
				
				var temp = {
                    name:d.index,
                    children:[]
                };
                
                var treeData = toTreeData(linksBak);
                
                function toTreeData(data){
                	console.log(data);
                	var pos={};
			        var tree=[];
			       
			        if(data.length>0){
			        	for(var i=0;i<data.length;i++){
			        		
			        		console.log(data[i].source);
			        	}
			        }
			        
			        /*while(data.length!=0){
			        	console.log(data[i].source.index);
			        }*/
	    /*console.log(tree);*/
	    /*}
			}
		})*/

	    //将数据整理为树状结构
	    /*nodesBak.forEach(function(d){
			
            if(d.index == 0){
                var temp = {
                    name:d.index,
                    children:[]
                };
                var treeData = toTreeData(linksBak);
                
                function toTreeData(data){
			    	console.log('ccc:'+data.length);
			        var pos={};
			        var tree=[];
			        var i=0;
			        while(data.length!=0){
			        	//console.log('source:'+data[i].source.index)
			            if(data[i].source.index==d.index){
			                tree.push({
			                    name:data[i].target.index,
			                    children:[]
			                });
			                pos[data[i].target.index]=[tree.length-1];
			                data.splice(i,1);
			                i--;
			            }else{
			                var posArr=pos[data[i].source.index];
			                if(posArr!=undefined){
			
			                    var obj=tree[posArr[0]];
			                    for(var j=1;j<posArr.length;j++){
			                        obj=obj.children[posArr[j]];
			                    }
			
			                    obj.children.push({
			                        name:data[i].target.index,
			                        children:[]
			                    });
			                    pos[data[i].target.index]=posArr.concat([obj.children.length-1]);
			                    data.splice(i,1);
			                    i--;
			                }
			            }
			            i++;
			            if(i>data.length-1){
			                i=0;
			            }
			        }
			        return tree;
			    }
                temp.children = treeData;
                middleData = temp;
                console.log(12);
            }console.log(middleData);
        });*/
	    /*//使用树状布局计算位置
	  	var tree = d3.layout.tree()
	            .size([450,450]);
	  	var tempNodes = tree.nodes(middleData);
	  	//重启布局以改变位置
	  	force.start();
	  	force.on("tick",function(){
	  		//在运动前强制修改节点坐标为树状结构
		    tempNodes.forEach(function(d,i){
			    nodes[d.name].x = d.x;
			    nodes[d.name].y = d.y
		 	});
	        linkG.attr("x1", function (d) {
	            return d.source.x;
	        })
	        .attr("y1", function (d) {
	            return d.source.y+10;
	        })
	        .attr("x2", function (d) {
	            return d.target.x;
	        })
	        .attr("y2", function (d) {
	            return d.target.y+10;
	        });
      		nodeG.attr("cx", function (d) {
                return d.x
            })
            .attr("cy", function(d){
              	return d.y+10
            });
  		})*/
	}